from django.shortcuts import render
from rest_framework import viewsets, mixins
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from alipay import AliPay
from django.conf import settings
from shopping.settings import APP_PRIVATE_KEY, ALIPAY_PUBLIC_KEY
from rest_framework.response import Response
from datetime import datetime

from utils.permissions import IsOwnerOrReadOnly
from .models import ShoppingCart, OrderInfo, OrderGoods
from .serializer import ShoppingCartSerializer, ListShoppingCartSerializer, OrderSerializer, \
    OrderDetailSerializer, OrderDetailSerializer


class ShoppingCartViewSet(viewsets.ModelViewSet):
    # 验证方式
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    # 设置权限
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    queryset = ShoppingCart.objects.all()
    serializer_class = ShoppingCartSerializer
    lookup_field = 'goods_id'

    def get_serializer_class(self):
        if self.action == 'list':
            return ListShoppingCartSerializer
        elif self.action == 'create':
            return ShoppingCartSerializer

        return ShoppingCartSerializer

    def get_queryset(self):
        return ShoppingCart.objects.filter(user=self.request.user)


class OrderViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin,
                   viewsets.GenericViewSet):
    """
    订单管理
    list:
        获取个人订单
    delete:
        删除订单
    create：
        新增订单
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = OrderSerializer

    def get_queryset(self):
        return OrderInfo.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == "retrieve":
            return OrderDetailSerializer
        return OrderSerializer

    def perform_create(self, serializer):
        order = serializer.save()
        # 获取到用户购物车里的商品
        shop_carts = ShoppingCart.objects.filter(user=self.request.user)
        for shop_cart in shop_carts:
            order_goods = OrderGoods()
            order_goods.goods = shop_cart.goods
            order_goods.goods_num = shop_cart.nums
            order_goods.order = order
            order_goods.save()

            shop_cart.delete()
        return order


# 支付宝支付结果验证
class AliPayView(APIView):
    """
   支付结果
   """

    # def get(self, request):

    def post(self, request):
        data_dict = {}

        for key, value in request.POST.items():
            data_dict[key] = value

        sing = data_dict.pop("sign", None)

        # 读取私钥
        app_private_key_string = open(APP_PRIVATE_KEY).read()
        # 读取公钥
        alipay_public_key_string = open(ALIPAY_PUBLIC_KEY).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # APPID
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,  # 私钥
            alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True,  # 是否调试模式
        )

        success = alipay.verify(data_dict, sing)
        print('我是POST')
        print(success)

        if success and data_dict["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            print('支付成功')
            order_sn = data_dict.get('order_sn',None)        #我们自己生成的订单号
            trade_no = data_dict.get('trade_no',None)      #支付宝订单交易号
            trade_status = data_dict.get('trade_status',None)      #订单状态

            #更新交易信息
            existed_OrderInfo =OrderInfo.objects.filter(order_sn=order_sn)

            for i in existed_OrderInfo:
                i.order_sn = order_sn
                i.trade_no = trade_no
                i.pay_status = trade_status
                i.pay_time = datetime.now()     #保存订单完成更新时间
                i.save()

            return Response("success")      #一定要给支付宝返回